﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using Microsoft.Reporting.WebForms;
using System.Web.UI.HtmlControls;

namespace Web.ChartReport
{
    public static class ReportViewHelper
    {
        /// <summary>
        /// 给报表添加每页条数. Udi 2012年3月2日
        /// </summary>
        /// <param name="Report"></param>
        /// <param name="hdPageSize"></param>
        public static void AddPageSize(this ReportViewer Report, HtmlInputHidden hdPageSize, Control Button)
        {
            var toolBar = FindToolBar(Report.Controls, "Microsoft.Reporting.WebForms.ToolbarControl");

            //第1个是页码组,第2个是缩放组. 有依赖性.
            var zoomGroup = toolBar.Controls[1];

            var label = new LiteralControl();
            label.ID = "lab_PageSize";

            var items = new int[] { 5, 10, 20, 50 };
            var options = new List<string>();
            for (int i = 0; i < items.Length; i++)
            {
                options.Add(string.Format(@"<option value='{0}' {1}>{0}</option>", items[i], hdPageSize.Value == items[i].ToString() ? "selected" : ""));
            }

            label.Text = string.Format(@"每页条数: <select onchange=""{0}"" style='width:40px'>{1}</select>",
                string.Format(@"(function(item){{$('#{0}').val($(item).val()); $('#{1}').trigger('click');}})(this);",
                hdPageSize.ClientID,
                Button.ClientID),
                string.Join("", options.ToArray()));
            zoomGroup.Controls.AddAt(0, label);
        }

        private static Control FindToolBar(ControlCollection ReportControls, string FullTypeName)
        {
            foreach (Control item in ReportControls)
            {
                if (item.ToString() == FullTypeName) return item;
                if (item.HasControls())
                {
                    var subFind = FindToolBar(item.Controls, FullTypeName);
                    if (subFind != null) return subFind;
                }
            }
            return null;
        }

        /// <summary>
        /// 给 ReportViewer 添加控件.
        /// this.ReportViewer1.AddToolControl(5, 0, new LiteralControl() { Text = string.Format(@"<a class='expBtn' onclick=""document.getElementById('{0}').click();"">导出</>", this.btn_Excel.ClientID) });
        /// </summary>
        /// <param name="Report"></param>
        /// <param name="GroupIndex">组索引</param>
        /// <param name="ControlIndex">组内控件索引</param>
        /// <param name="Control"></param>
        public static void AddToolControl(this ReportViewer Report, int GroupIndex, int ControlIndex, Control Control)
        {
            var toolBar = FindToolBar(Report.Controls, "Microsoft.Reporting.WebForms.ToolbarControl");

            var zoomGroup = toolBar.Controls[GroupIndex];


            zoomGroup.Controls.AddAt(ControlIndex, Control);
        }
    }
}
